package test.synccall;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.async.DeferredResult;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingDeque;

/**
 * @Classname TaskQueue
 * @Description TODO
 * @Date 2022/3/22 9:10
 * @Created by KangJonney
 */
@Component
public class TaskQueue {
    private static final Logger log = LoggerFactory.getLogger(TaskQueue.class);

    private static final int QUEUE_LENGTH = 10;

    /**
     * 实际的队列为成员变量queue，它是LinkedBlockingDeque类型的
     */
    private BlockingQueue<Task> queue = new LinkedBlockingDeque<>(QUEUE_LENGTH);

    /**
     * 一个成员变量为taskId，是用于自动生成任务id的，并且在加入任务的方法中实现自增，以确保每个任务的id唯一性
     */
    private int taskId = 0;

    /**
     * 给队列加入任务
     * @param deferredResult
     */
    public void put(DeferredResult<ResponseMsg<String>> deferredResult){

        taskId++;

        log.info("任务加入队列，id为：{}",taskId);

        queue.offer(new Task(taskId,deferredResult));

    }

    /**
     * 在队列中获取任务
     * @return
     * @throws InterruptedException
     */
    public Task take() throws InterruptedException {

        Task task = queue.poll();

        log.info("获得任务:{}",task);

        return task;
    }
}
